﻿package pl.krasi.game{

	/*
	Imports
	*/
	import flash.utils.*;
	import flash.events.*;
	import gs.TweenLite;
	import gs.TweenMax;
	import fl.motion.easing.*;

	import fl.motion.easing.*;
	import flash.display.*;
	import pl.krasi.game.Display;
	
	import gs.plugins.*;
	import gs.easing.*;



	
	//!!import com.egrGlobal.GameControlEvent;

	public class Snake extends Sprite {

		private var minisList:Array;
		private var snake:Array;
		private var gameTimer:Timer;
		private var tempArray:Array=new Array;
		private var _direction:uint;
		private var _Tdirection:uint;
		private var _headX:int;
		private var _headY:int;
		private var special;
		private static  var child;
		private var _score:uint = 0;
		public var score:Number = 0;
		private var display:Display;
		private var colorTable:Array = new Array();

		/**
		* Przekazywane jest obiekt, ktory jest zbiorem "pixeli" - w tym wypadku miniatury ze zdjęc.
		*/
		public function Snake(obj:Display,listener:Stage) {
			minisList=obj.minisList;
			display = obj;
			snake = new Array  ;
			
			//color guide for levels
			colorTable.push(0x00CCFF);
			colorTable.push(0x0099FF);
			colorTable.push(0x0066CC);
			colorTable.push(0xCCCCFF);
			colorTable.push(0xCCFFCC);
			colorTable.push(0xCCFF99);
			colorTable.push(0xCCFF66);
			colorTable.push(0x33FF99);
			colorTable.push(0x33FF66);
			colorTable.push(0x33CC00);
			colorTable.push(0x339900);
			colorTable.push(0xFFFFCC);
			colorTable.push(0xFFFF66);
			colorTable.push(0xFFCC33);
			colorTable.push(0xFF9933);
			colorTable.push(0xFF9966);
			colorTable.push(0xFF6666);
			colorTable.push(0xFF3366);
			colorTable.push(0xFF3399); 
			//
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			colorTable.push(0xFF3399); 
			_score = 0 ;

			listener.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
			TweenPlugin.activate([BevelFilterPlugin]);
			
			for (var i:uint=0; i < minisList.length; i++) {
				for (var j:uint=0; j < minisList[i].length; j++) {
				TweenMax.to(minisList[i][j], 1, {tint: null, colorMatrixFilter:{colorize:colorTable[0]}, bevelFilter: { distance:0, strength:0, blurX:0, blurY:0, angle:0 }, ease:Quad.easeOut});
				}
			}
			

			startGame();


		}
		private function startGame():void {
			clrScr()
			//ustawienie pozycji startowej weza
			_headX=Math.floor(Math.random() * 15) + 5;
			_headY=Math.floor(Math.random() * 5) + 4;

			//ustawienie kierunku
			_direction=Math.floor(Math.random() * 3.99);
			//inicjalizacja węża
			snake.push(minisList[_headX][_headY]);
			for (var i:uint=1; i < 5; i++) {
				switch (_direction) {
					case 0 :
						snake.push(minisList[_headX][_headY + i]);
						break;
					case 1 :
						snake.push(minisList[_headX + i][_headY]);
						break;
					case 2 :
						snake.push(minisList[_headX][_headY - i]);
						break;
					case 3 :
						snake.push(minisList[_headX - i][_headY]);
						break;
				}
			}
			//wstawienie specjału
			addFood();

			//render
			render();
			gameTimer=new Timer(70,0);
			gameTimer.addEventListener(TimerEvent.TIMER,calculateMove);
			//gameTimer.addEventListener(TimerEvent.TIMER_COMPLETE, stopCalculateLife);
			gameTimer.start();
		}

		public function stop() {
			gameTimer.stop();
		}		

		private function calculateMove(e:TimerEvent):void {
			deRender();
			
			//Zabezpieczenie przed "zawracaniem"
			//_direction - zawiera kierunek w którym aktualnie porusza się wąż
			//_Tdirection - kierunek wybrany przez wciśnięcie przycisku.
			if (_direction == 0) {
				if (_Tdirection != 2) {
					_direction = _Tdirection;
				}
			}
			if (_direction == 1) {
				if (_Tdirection != 3) {
					_direction = _Tdirection;
				}
			}
			if (_direction == 2) {
				if (_Tdirection != 0) {
					_direction = _Tdirection;
				}
			}
			if (_direction == 3) {
				if (_Tdirection != 1) {
					_direction = _Tdirection;
				}
			}
			//zmiana polozenia glowy weza
			switch (_direction) {
				case 0 :
					_headY--;
					break;
				case 1 :
					_headX--;
					break;
				case 2 :
					_headY++;
					break;
				case 3 :
					_headX++;
					break;
			}
			//PRzechodzenie przez ściany
			if (_headY == 16) {
				_headY=0;
			}
			if (_headY == -1) {
				_headY=15;
			}
			if (_headX == 25) {
				_headX=0;
			}
			if (_headX == -1) {
				_headX=24;
			}
			//Sprawdzenie czy nie ugryźliśmy siebie
			for (var i:uint=0; i < snake.length; i++) {

				if (snake[i] == minisList[_headX][_headY]) {
					//koniec gry\
					initEnd();
					//endGame();
					break;
				}
			}
			//sprawdzenie czy jedzonko
			if (minisList[_headX][_headY] == special) {
				snake.push(snake[snake.length - 1]);
				addFood();
				_score += 8;
				
				if (_score % 80 == 0) {
					changeColor()
				}

			}

			//przesuniecie reszty ciala
			for (i=snake.length - 1; i > 0; i--) {

				snake[i]=snake[i - 1];
			}
			snake[0]=minisList[_headX][_headY];

			//render

			render();
		}
		
		private function changeColor() : void {
			//TweenMax.to(ldr, 1, {colorMatrixFilter:{colorize:0xff0000}});
			for (var i:uint=0; i < minisList.length; i++) {
				for (var j:uint=0; j < minisList[i].length; j++) {
					TweenMax.to(minisList[i][j], 1, {colorMatrixFilter:{colorize:colorTable[Math.floor(_score/80)]}});
				}
			}
		}
		public function initEnd():void {
			trace("fra sie zakonczyla. goddamit!")
			gameTimer.stop();
			//TweenLite.to(minisList[_headX][_headY], .01, {tint:null, onComplete:endGame});			
			endGame();
		}
		private function addFood():void {
			special=minisList[Math.floor(Math.random() * 24.99)][Math.floor(Math.random() * 15.99)];
			for (var i:uint=0; i < snake.length; i++) {
				if (snake[i] == special) {
					addFood();
					break;
				}
			}
		}
		private function deRender():void {
			var i = snake.length-1;
			snake[i].alpha=1;
			for (i; i>=0; i--) {
				
				//TweenLite.to(snake[i], 0, { tint:null, bevelFilter: { distance:0, strength:0, blurX:0, blurY:0, angle:0 }} )
				TweenLite.to(snake[i], 0, { tint:null, bevelFilter: { distance:0, strength:0, blurX:0, blurY:0, angle:0 } } )
				
				snake[i].alpha = 1;
				//TweenLite.to(snake[i], 0, {tint:null});
			}
		}
		private function clrScr():void {
			for (var i:uint=0; i < minisList.length; i++) {
				for (var j:uint=0; j < minisList[i].length; j++) {
					minisList[i][j].alpha=1;

				}
			}
		}
		private function render():void {

			for (var i:uint=0; i < snake.length; i++) {
				snake[i].alpha=5;
				//TweenLite.to(snake[i],0,{bevelFilter:{distance:5,strength:1,blurX:5,blurY:5,angle:45}});
				TweenLite.to(snake[i], 0, {tint:null, bevelFilter:{distance:5,strength:1,blurX:5,blurY:5,angle:45}});
				//TweenFilterLite.to(snake[0], 0, {});
			}
			snake[0].alpha=10;
			TweenLite.to(snake[0], 0, {tint:0x0F907E});

			try {
				special.alpha=10;
			} catch (e:Error) {
			}
		}

		private function keyDownHandler(event:KeyboardEvent):void {
			trace("keyDownHandler: " + event.keyCode);
			switch (event.keyCode) {
				case 38 :
					//if (_direction!=2) {
					_Tdirection=0;
					//}
					break;
				case 37 :
					//if (_direction!=3) {
					_Tdirection=1;
					//}
					break;
				case 39 :
					//if (_direction!=1) {
					_Tdirection=3;
					//}
					break;
				case 40 :
					//if (_direction!=0) {
					_Tdirection=2;
					//}
					break;
			}
		}
		private function showScore() {
			trace("Wynik: "  + _score)
			/*display.instantResetAlpha();
			var btp = new Loose(45,22);
			//trace (btp as BitmapData)
			var bitData:BitmapData =(btp as BitmapData);
			for (var i:uint = 0; i<45; i++) {
				for (var j:uint = 0; j<22; j++) {
					if (bitData.getPixel(i,j) ==0 ) {
						TweenLite.to(minisList[i][j], .5, {alpha:10,delay:Math.random()*.5, ease:Sine.easeInOut});
					} else {
						minisList[i][j].alpha =1;
					}
				}
			}
			sc = new Score()
			sc.score.text = "Your score: " + _score + " PTS :)";
			sc.x = 18*22 + 71;
			sc.y =  21*22 + 25;
			TweenLite.from(sc, .6, {alpha:0, delay:.1, ease:Sine.easeInOut});
			TweenLite.to(sc, .6, {alpha:0, delay:3, ease:Sine.easeInOut,onComplete:removeScore});
			display.addChild(sc)			
			setTimeout(launchConway,3500);*/
		}
		private function launchConway() {
			//var cw = new Conway(display);
		}
		private function removeScore():void {
			//display.removeChild(sc)
		}

		public function endGame():void {
			trace("Koniec GRY");
			gameTimer.stop();		
			
			score = _score;
			dispatchEvent(new Event(Event.CHANGE));
			
			/*display.fullResetAlpha(snake);
			
			dispatchEvent(new GameControlEvent("endGame"));
			setTimeout(showScore,20);
			//Wyświetlenie wyniku i informacji o porażce
			//coś tam o highscors*/
		}
	
		//--------EndOfClass
	}
}